<?php

namespace App\Http\Controllers\Backend\Setting;

use App\Constants\RedisKey;
use App\Events\SettingLogEvent;
use App\Http\Requests\Backend\Setting\SettingHomeInsuranceRequest;
use App\Models\SettingHomeInsurance;
use App\Models\SettingLog;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Failed;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use test\Mockery\SubclassWithFinalWakeup;

class SettingHomeInsuranceController extends Controller
{
    use \App\Library\Traits\SettingLog;
    const SETTING_TABLE = "setting_home_insurances";
    public function __construct()
    {
        $this->middleware('auth:backend');
        $this->user = auth('backend')->user();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $settingHomeInsurance = new SettingHomeInsurance();
        $settingHomeInsurance->setConnection('backend');
        $insuranceInfo = $settingHomeInsurance->orderBy('sort_id','asc')->get();
        foreach ($insuranceInfo as $k => &$v){
            $v['path'] = $v['img_url'];
            $v['img_url'] = getOssUrl($v['img_url']);
        }
        return success($insuranceInfo);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(SettingHomeInsuranceRequest $request)
    {
        $info = $this->extractInputFromRules($request,$request->rules());
        $result = SettingHomeInsurance::create($info);
        if($result){
            $this->setting_log($this->user->id,self::SETTING_TABLE,$result->id,SettingLog::LOG_INSERT,$info);
            return stored('');
        }else{
            return failed('创建失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $settingHomeInsurance = new SettingHomeInsurance();
        $settingHomeInsurance->setConnection('backend');
        $insuranceInfo = $settingHomeInsurance->where('id',$id) -> first();
        if($insuranceInfo){
            $insuranceInfo['path'] = $insuranceInfo['img_url'];
            $insuranceInfo["img_url"] = getOssUrl($insuranceInfo["img_url"]);
            return success($insuranceInfo);
        }
        return failed('当前信息不存在');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(SettingHomeInsuranceRequest $request, $id)
    {
        $updateData = $request->only(['title','subtitle','button_name','url_set','img_url']);
        if(!empty($updateData['img_url'])){
            //删除原来的图片信息
            SettingHomeInsurance::deleteImage($id,$updateData['img_url']);
        }
        $info = SettingHomeInsurance::where('id',$id)->update($updateData);
        \Cache::delete(RedisKey::SETTING_HOME_INSURANCE);
        $this->setting_log($this->user->id,self::SETTING_TABLE,$id,SettingLog::LOG_UPDATE,$updateData);
        return updated('');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = SettingHomeInsurance::where('id',$id) -> delete();
        if($result){
            \Cache::delete(RedisKey::SETTING_HOME_INSURANCE);
            $this->setting_log($this->user->id,self::SETTING_TABLE,$id,SettingLog::LOG_DELETE);
            return deleted();
        }else{
            return failed('删除失败');
        }
    }

    /**
     * @Description up or down
     * @date 2019-04-17
     * @param Request $request
     * @return mixed
     * @throws \Exception11
     */

    public function changeSiteUpOrDown(Request $request) {
        $request_id = $request->input('sort_id');
        $type = $request->input('type',1); //remove sort ,1.up ,2.down
        $old_data = DB::table('setting_home_insurances')->where('sort_id','=',$request_id)->first();
        if (empty($old_data)) {
            return success('违法数据 !');
        }
        $old_id = $old_data->id;
        $old_sort_id = $old_data->sort_id;
        if($type != 1 && $type != 2) {
            return success('无效的状态类型');
        }

        if ($type == 1) {
            $new_data = DB::table('setting_home_insurances')
                                    ->where('sort_id','<',$old_sort_id)
                                    ->orderBy('sort_id','desc')
                                    ->first();

            if (empty($new_data)) {
                return success('当前属于第一位无法上移!');
            }else {
                $new_id = $new_data->id ;
                $new_sort_id = $new_data->sort_id ;

                DB::beginTransaction();
                try {
                    DB::table('setting_home_insurances')->where('id','=',$old_id)->update([
                        'sort_id'=>$new_sort_id
                    ]);
                    DB::table('setting_home_insurances')->where('id','=',$new_id)->update([
                        'sort_id'=>$old_sort_id
                    ]);
                    DB::commit();
                }catch (\Exception $exception) {
                    DB::rollback();
                    return success($exception->getMessage());
                }

                return success('ok');
            }
        }else {
            $new_data = DB::table('setting_home_insurances')
                ->where('sort_id','>',$old_sort_id)
                ->orderBy('sort_id','asc')
                ->first();
            if (empty($new_data)) {
                return success('当前属于最后一位无法下移 !');
            }else {
                $new_id = $new_data->id ;
                $new_sort_id = $new_data->sort_id ;

                DB::beginTransaction();
                try {
                    DB::table('setting_home_insurances')->where('id','=',$old_id)->update([
                        'sort_id'=>$new_sort_id
                    ]);
                    DB::table('setting_home_insurances')->where('id','=',$new_id)->update([
                        'sort_id'=>$old_sort_id
                    ]);
                    DB::commit();
                }catch (\Exception $exception) {
                    DB::rollback();
                    return success($exception->getMessage());
                }
                return success('ok');
            }
        }

    }
}
